"""
角色数据模式（Schema）定义
处理角色相关的请求与响应数据结构
"""
from typing import Optional, List
from datetime import datetime
from pydantic import BaseModel, Field, field_validator
import re


class RoleBase(BaseModel):
    """角色基础数据模型"""
    name: str = Field(..., min_length=2, max_length=50, description="角色名称")
    slug: str = Field(..., min_length=2, max_length=50, description="角色标识")
    description: Optional[str] = Field(None, description="角色描述")
    
    
    @field_validator('slug')
    def validate_slug(cls, v):
        if not re.match(r'^[a-z0-9_]+$', v):
            raise ValueError('角色标识只能包含小写字母、数字和下划线')
        return v


class RoleCreate(RoleBase):
    """创建角色请求模型"""
    is_system: bool = Field(False, description="是否为系统角色")


class RoleUpdate(BaseModel):
    """更新角色请求模型(部分更新)"""
    name: Optional[str] = Field(None, min_length=2, max_length=50)
    description: Optional[str] = None
    
    model_config = {"from_attributes": True}


class RoleWholeUpdate(RoleBase):
    """完整更新角色请求模型"""
    pass


class RoleResponse(RoleBase):
    """角色响应模型"""
    id: int
    is_system: bool
    created_at: datetime
    updated_at: datetime
    
    model_config = {"from_attributes": True}


class RoleListResponse(BaseModel):
    """角色列表响应模型"""
    items: List[RoleResponse]
    total: int
    page: int
    page_size: int
    pages: int


class RoleWithPermissionsResponse(RoleResponse):
    """带权限信息的角色响应模型"""
    permissions: List[int] = Field([], description="角色拥有的权限ID列表")
